<template>
  <div class="app-container">
    <!-- 当前章节下的视频信息显示区域 -->
    <el-card v-if="currentCourseInfo" class="mb-20" shadow="never">
      <div class="course-header">
        <el-row :gutter="20" align="middle">
          <el-col :span="18">
            <div class="course-title">
              <i class="el-icon-back" @click="goBack" style="cursor: pointer; margin-right: 10px; color: #409EFF;"></i>
              <span class="title-text">课程章节管理</span>
              <el-divider direction="vertical"></el-divider>
              <el-tag type="primary" size="medium">{{ currentCourseInfo.chapterName }}</el-tag>
            </div>
            <div class="course-subtitle">
              <span class="subtitle-text">当前查看：{{ currentCourseInfo.chapterName }} 的章节列表</span>
            </div>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-button type="primary" icon="el-icon-back" size="small" @click="goBack">
              返回课程列表
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="视频名称" prop="videoName">
        <el-input
          v-model="queryParams.videoName"
          placeholder="请输入视频名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节名称" prop="chapterName">
        <el-input
          v-model="queryParams.chapterName"
          placeholder="请输入章节名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="videoStatus">
        <el-select
          v-model="queryParams.videoStatus"
          placeholder="请选择状态"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option label="正常" :value="1"></el-option>
          <el-option label="删除" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['courseManagement:video:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['courseManagement:video:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['courseManagement:video:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['courseManagement:video:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="视频id" align="center" prop="videoId" />
      <el-table-column label="视频名称" align="center" prop="videoName" />
      <el-table-column label="章节名称" align="center" prop="chapterName" />
      <el-table-column label="视频大小(KB)" align="center" prop="videoSize" />
      <el-table-column label="视频类型" align="center" prop="videoType" />
      <el-table-column label="视频路径" align="center" prop="videoPath" />
      <el-table-column label="状态" align="center" prop="videoStatus">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.videoStatus == 1"
            >正常</el-tag
          >
          <el-tag type="danger" v-else>删除</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['courseManagement:video:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['courseManagement:video:edit']"
            >预览</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['courseManagement:video:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改视频管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="视频名称" prop="videoName">
          <el-input v-model="form.videoName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="所属章节" prop="chapterName">
          <el-select
            v-model="form.chapterId"
            clearable
            placeholder="请选择章节"
          >
            <el-option
              v-for="item in chapterList"
              :key="item.chapterId"
              :label="item.chapterName"
              :value="item.chapterId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频路径" prop="videoPath">
          <el-upload
            class="upload-demo"
            ref="upload"
            action=""
            :file-list="fileList"
            :http-request="uploadVideo"
            :before-upload="beforeUpload"
            :on-error="handleUploadError"
            accept=".mp4,.mp4k,.avi,.mov,.wmv,.flv,.webm,.mkv,.m4v,.3gp,.ogv"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取视频文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传视频文件，且不超过80MB
              <br>
              支持的格式：MP4, AVI, MOV, WMV, FLV, WebM, MKV, M4V, 3GP, OGV
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频大小" prop="videoSize">
          <el-input v-model="form.videoSize" placeholder="请上传视频文件" disabled/>
        </el-form-item>
        <el-form-item label="视频类型" prop="videoType">
          <el-input v-model="form.videoType" placeholder="请上传视频文件" disabled/>
        </el-form-item>
         <el-form-item label="状态" prop="videoStatus">
          <el-radio-group v-model="form.videoStatus">
            <el-radio :label="0">删除</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog 
      :title="previewTitle" 
      :visible.sync="previewVisible" 
      width="80%" 
      append-to-body
      :before-close="handlePreviewClose"
      @keyup.esc="previewVisible = false"
    >
      <!-- 文件信息 -->
      <div class="file-info" style="margin-bottom: 15px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <span class="info-label">文件类型：</span>
            <el-tag size="small" :type="getFileTypeTagType(previewFileType)">{{ (previewFileType || '未知').toUpperCase() }}</el-tag>
          </el-col>
          <el-col :span="8">
            <span class="info-label">视频大小：</span>
            <span>{{ formatFileSize(previewFileSize) }}</span>
          </el-col>
          <el-col :span="8">
            <span class="info-label">支持预览：</span>
            <el-tag size="small" :type="isPreviewSupported() ? 'success' : 'warning'">
              {{ isPreviewSupported() ? '是' : '否' }}
            </el-tag>
          </el-col>
        </el-row>
      </div>
      
      <div class="preview-container">
        <!-- 加载状态 -->
        <div v-if="previewLoading" class="loading-container">
          <i class="el-icon-loading"></i>
          <p>正在加载文件...</p>
        </div>
        <!-- 视频预览 -->
        <div v-else-if="isVideoFile" class="video-preview">
          <video 
            :src="previewFileUrl" 
            controls 
            style="width: 100%; max-height: 500px;"
          >
            您的浏览器不支持视频播放
          </video>
        </div>
        <!-- 不支持的文件类型 -->
        <div v-else class="unsupported-file">
          <i class="el-icon-document file-type-icon"></i>
          <el-alert
            title="不支持的文件类型"
            :description="`当前文件类型 ${previewFileType || '未知'} 不支持在线预览，请下载后查看`"
            type="warning"
            show-icon
            :closable="false"
          >
            <template slot="default">
              <el-button type="primary" size="small" @click="downloadFile">
                下载文件
              </el-button>
            </template>
          </el-alert>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关 闭</el-button>
        <el-button type="primary" @click="downloadFile">下 载</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listVideo, getVideo, delVideo, addVideo, updateVideo } from "@/api/courseManagement/video"
import { listChapter } from "@/api/courseManagement/chapter";
import { uploadIdCard } from "@/api/artGood/artGood";
import Cookies from "js-cookie";

export default {
  name: "Video",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 当前章节信息
      currentCourseInfo: null,
      // 视频管理表格数据
      videoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      campusId:null,
      // 章节列表
      chapterList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        videoName: null,
        chapterName: null,
        campusId: null,
        videoStatus: null,
      },
      // 表单参数
      form: {
        videoStatus:1,
        campusId: null
      },
      // 表单校验
      rules: {
      },
      // 上传的文件列表
      fileList: [],
      // 预览相关属性
      previewTitle: "",
      previewVisible: false,
      previewFileUrl: "",
      previewFileType: "",
      previewFileSize: 0,
      previewLoading: true,
      isVideoFile: false
    }
  },
  created() {
    const user= JSON.parse(Cookies.get("user"))
    this.campusId = user.campusId
    this.form.campusId = this.campusId;
    this.queryParams.campusId = this.campusId;
    // 接收从章节页面传递过来的参数
    this.receiveParams();
    this.getList()
  },
  methods: {
     // 接收传递的参数
    receiveParams() {
      this.reset();
      const chapterId = this.$route.query.chapterId;
      const chapterName = this.$route.query.chapterName;
      // 如果有传递课程ID，则设置到查询参数中
      if (chapterId) {
        this.queryParams.chapterId = chapterId;
        // 如果有课程名称，也设置到查询参数中
        if (chapterName) {
          this.queryParams.chapterName = chapterName;
        }
        
        // 设置当前课程信息
        this.currentCourseInfo = {
          chapterId: chapterId,
          chapterName: chapterName || '未知课程'
        };
        
        // 显示消息提醒
        this.$message({
          message: `已切换到章节：${chapterName} 的课件管理`,
          type: 'success',
          duration: 3000,
          showClose: true
        });
      }
    },
        // 返回章节列表
    goBack() {
      this.$router.push('/courseManagement/chapter');
    },
    /** 查询视频管理列表 */
    getList() {
      this.loading = true
      listVideo(this.queryParams).then(response => {
        this.videoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询课程章节列表 */
    getChapterList() {
      listChapter(this.queryParams).then((response) => {
        this.chapterList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        videoId: null,
        videoName: null,
        videoDuration: null,
        videoPath: null,
        campusId:this.campusId,
        videoSize: null,
        videoType:null,
        videoStatus: 1,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.videoId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getChapterList();
      this.open = true
      this.title = "添加视频管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getChapterList();
      const videoId = row.videoId || this.ids
      getVideo(videoId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改视频管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.videoId != null) {
            updateVideo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addVideo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const videoIds = row.videoId || this.ids
      this.$modal.confirm('是否确认删除视频管理编号为"' + videoIds + '"的数据项？').then(function() {
        return delVideo(videoIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('courseManagement/video/export', {
        ...this.queryParams
      }, `video_${new Date().getTime()}.xlsx`)
    },
    
    // 上传视频文件
    uploadVideo(item) {
      // 上传文件需要formdata类型
      const formdata = new FormData();
      formdata.append("file", item.file);
      
      // 使用与课件管理相同的上传接口
      uploadIdCard(formdata).then((res) => {
        this.$modal.msgSuccess(`视频上传成功！文件名：${item.file.name}，大小：${(item.file.size / 1024 / 1024).toFixed(2)}MB`);
        this.form.videoPath = res.data.file.url;
        this.form.videoSize = res.data.file.size;
        this.form.videoType = res.data.file.contentType;
        this.fileList = [
          {
            videoName: item.file.name,
            videoPath: res.data.file.url,
            videoType: res.data.file.contentType,
            videoSize: res.data.file.size,
          },
        ];
        
      }).catch((error) => {
        console.error('视频上传失败:', error);
        this.$modal.msgError('视频上传失败，请重试');
      });
    },
    
    // 上传前验证文件
    beforeUpload(file) {
      // 检查文件大小 (80MB = 80 * 1024 * 1024 bytes)
      const maxSize = 80 * 1024 * 1024;
      if (file.size > maxSize) {
        this.$modal.msgError(`视频大小不能超过80MB，当前文件大小: ${(file.size / 1024 / 1024).toFixed(2)}MB`);
        return false;
      }
      
      // 检查文件类型
      const allowedVideoTypes = ['mp4', 'mp4k', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv', 'm4v', '3gp', 'ogv'];
      const fileName = file.name;
      const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
      
      if (!allowedVideoTypes.includes(fileExtension)) {
        this.$modal.msgError(`不支持的文件格式: ${fileExtension}，只能上传视频文件`);
        return false;
      }
      
      // 显示文件信息
      // console.log(`准备上传视频: ${fileName}, 大小: ${(file.size / 1024 / 1024).toFixed(2)}MB, 类型: ${fileExtension}`);
      
      return true;
    },
    
    // 上传错误处理
    handleUploadError(err, file, fileList) {
      console.error('视频上传失败:', err);
      this.$modal.msgError('视频上传失败，请重试');
    },
    /** 查看视频按钮 */
    handleView(row) {
      this.previewFile(row);
    },
    // 文件预览相关方法
    previewFile(row) {
      if (!row.videoPath) {
        this.$modal.msgError("视频路径不存在");
        return;
      }
      this.previewLoading = true;
      try {
        this.previewTitle = `预览 - ${row.videoName}`;
        // 处理文件URL路径
        let fileUrl = row.videoPath;
        if (fileUrl && !/^https?:\/\//.test(fileUrl)) {
          fileUrl = process.env.VUE_APP_BASE_API + fileUrl;
        }
        this.previewFileUrl = fileUrl;
        this.previewFileType = row.videoType || '';
        this.previewFileSize = row.videoSize || 0;
        // 判断文件类型
        this.isVideoFile = this.isVideo(row.videoType);
        this.previewVisible = true;
        this.previewLoading = false;
      } catch (error) {
        console.error('预览文件失败:', error);
        this.$modal.msgError("预览文件失败，请检查文件路径和类型");
        this.previewLoading = false;
      }
    },
    // 关闭预览对话框
    handlePreviewClose() {
      this.previewTitle = "";
      this.previewVisible = false;
      this.previewFileUrl = "";
      this.isVideoFile = false;
      this.previewFileType = "";
      this.previewFileSize = 0;
      this.previewLoading = false;
    },
    // 判断文件是否支持预览
    isPreviewSupported() {
      if (!this.previewFileType) {
        return false;
      }
      return this.isVideo(this.previewFileType)

    },
    // 判断是否为视频文件
    isVideo(fileType) {
      if (!fileType) return false;
      const videoTypes = ['mp4', 'mp4k', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv', 'm4v', '3gp', 'ogv','video/mp4'];
      return videoTypes.includes(fileType.toLowerCase());
    },
    // 获取文件类型标签样式
    getFileTypeTagType(type) {
      if (!type) return 'info';
      const t = type.toLowerCase();
      if ([
        'mp4', 'mp4k', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv', 'm4v', '3gp', 'ogv'
      ].includes(t)) return 'success';
      return 'info';
    },
    // 文件大小格式化
    formatFileSize(size) {
      if (!size && size !== 0) return '未知';
      if (size < 1024) return size + ' B';
      if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB';
      if (size < 1024 * 1024 * 1024) return (size / 1024 / 1024).toFixed(2) + ' MB';
      return (size / 1024 / 1024 / 1024).toFixed(2) + ' GB';
    },
    // 下载文件
    downloadFile() {
      if (!this.previewFileUrl) {
        this.$modal && this.$modal.msgError ? this.$modal.msgError("没有可下载的文件地址") : alert("没有可下载的文件地址");
        return;
      }
      window.open(this.previewFileUrl, '_blank');
    },
  }
}
</script>
<style>
.el-form-item__label{
  font-size:13px
}
.mb-20 {
  margin-bottom: 20px;
}

.course-header {
  padding: 10px 0;
}

.course-title {
  display: flex;
  align-items: center;
}

.title-text {
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}

.course-subtitle {
  margin-top: 5px;
}

.subtitle-text {
  color: #606266;
  font-weight: 500;
}
</style>
